package net.zigin.nhi.waste.adapter;

import android.annotation.SuppressLint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.bean.BatchInBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.depotin.BatchBindActivity;
import net.zigin.nhi.waste.view.widget.DialogManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.paperdb.Paper;
import io.reactivex.Observable;

public class BatchBindAdapter extends RecyclerView.Adapter<BatchBindAdapter.ViewHolder>{

    public List<BatchInBean> list;
    private String collectorName;
    private IActivityUpData dd;
    private boolean isItemCheck = false;

    private List<BatchInBean> newList;

    public BatchBindAdapter(List<BatchInBean> list, IActivityUpData dd, String collectorName) {
        this.list = list;
        this.dd = dd;
        this.collectorName = collectorName;
        newList = new ArrayList<>();
    }

    public void notifyData(List<BatchInBean> beanList) {
        if (beanList != null) {
            list = new ArrayList<>();
            list.addAll(beanList);
        }
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bind_batch, parent, false);
        return new ViewHolder(view);
    }

    @Override
    @SuppressLint("RecyclerView")
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BatchInBean bean = list.get(position);
        holder.mWeight.setText(bean.getWeight());
        holder.mHospitalName.setText(bean.getHospitalBaseName());
        holder.mDepartName.setText(bean.getHospitalDepartName());
        holder.mConsignee.setText(collectorName);
        holder.mPublisher.setText(bean.getHandUserStaffName());
        holder.mType.setText(bean.getWasteClassifyName());
        holder.mTime.setText(bean.getCreateTime());

        boolean isCheck = bean.isSelect();
        if (isCheck) {
            isItemCheck = true;
            holder.mImg.setImageResource(R.drawable.depot_in_selected);
        } else {
            isItemCheck = false;
            holder.mImg.setImageResource(R.drawable.depot_in_unselected);
        }

        if (!newList.contains(bean)) {
            newList.add(bean);
            Paper.book().write(Constants.NEW_BATCH_LIST, newList);
        }

        holder.mLayout.setOnClickListener(v -> {
            if (isItemCheck) {
                newList.remove(bean);
                isItemCheck = false;
                holder.mImg.setImageResource(R.drawable.depot_in_unselected);
                bean.setSelect(false);
                dd.upDataUi();

                newList.add(bean);
                Paper.book().write(Constants.NEW_BATCH_LIST, newList);
            } else {
                newList.remove(bean);
                isItemCheck = true;
                holder.mImg.setImageResource(R.drawable.depot_in_selected);
                bean.setSelect(true);

                newList.add(bean);
                Paper.book().write(Constants.NEW_BATCH_LIST, newList);
            }
        });

        holder.mDepot.setOnClickListener(v -> {
            String boxBindWasteType = Paper.book().read(Constants.BOX_BIND_WASTE_TYPE);
            if (StringUtil.isNotEmpty(boxBindWasteType)) {
                if (boxBindWasteType.equals(bean.getWasteClassifyCode())) {
                    Set<String> idSet = new HashSet<>();
                    idSet.add(bean.getId());
                    String qrCode = Paper.book().read(Constants.BOX_CODE);
                    Map<String, Object> map = new HashMap<>();
                    map.put("wasteBoxQrCode", qrCode);
                    map.put("wasteBaseIds", idSet);
                    Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                            .bindBagWithBox(Paper.book().read(Constants.TOKEN), map);
                    DialogManager.getInstance().showLoading(v.getContext());
                    HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                        @Override
                        protected void success(String data) {
                            Log.i("箱袋绑定", data);
                            Paper.book().write(Constants.BOX_ID, data);
                            Paper.book().write(Constants.BOX_BIND_WASTE_TYPE, bean.getWasteClassifyCode());
                            Toast.makeText(v.getContext(), "袋装绑定成功！", Toast.LENGTH_SHORT).show();
                            list.remove(position);
                            notifyItemRemoved(position);
                            notifyItemRangeChanged(position, list.size() - position);
                        }
                    });
                } else {
                    Toast.makeText(v.getContext(), "请绑定与箱袋中相同类型的医废！", Toast.LENGTH_SHORT).show();
                }
            } else {
                Set<String> idSet = new HashSet<>();
                idSet.add(bean.getId());
                String qrCode = Paper.book().read(Constants.BOX_CODE);
                Map<String, Object> map = new HashMap<>();
                map.put("wasteBoxQrCode", qrCode);
                map.put("wasteBaseIds", idSet);
                Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                        .bindBagWithBox(Paper.book().read(Constants.TOKEN), map);
                DialogManager.getInstance().showLoading(v.getContext());
                HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                    @Override
                    protected void success(String data) {
                        Log.i("箱袋绑定", data);
                        Paper.book().write(Constants.BOX_ID, data);
                        Paper.book().write(Constants.BOX_BIND_WASTE_TYPE, bean.getWasteClassifyCode());
                        Toast.makeText(v.getContext(), "袋装绑定成功！", Toast.LENGTH_SHORT).show();
                        list.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, list.size() - position);
                    }
                });
            }


        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private LinearLayout mLayout;
        private ImageView mImg;
        private TextView mWeight;
        private TextView mHospitalName;
        private TextView mDepartName;
        private TextView mType;
        private TextView mPublisher;
        private TextView mConsignee;
        private TextView mTime;
        private Button mDepot;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mLayout = itemView.findViewById(R.id.layout);
            mImg = itemView.findViewById(R.id.img);
            mWeight = itemView.findViewById(R.id.weight);
            mHospitalName = itemView.findViewById(R.id.hospitalName);
            mDepartName = itemView.findViewById(R.id.departName);
            mType = itemView.findViewById(R.id.type);
            mPublisher = itemView.findViewById(R.id.publisher);
            mConsignee = itemView.findViewById(R.id.consignee);
            mTime = itemView.findViewById(R.id.time);
            mDepot = itemView.findViewById(R.id.depot);
        }
    }
}
